import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { verifyAuth } from './utils/Auth/auth';
import { backMessage } from './utils/tools';

const whiteList = ['/api/login/login', '/api/tapd/story/updateStatus', '/api/gitlab/hooks', '/api/gitlab/recentBranches'];

// 删除url最后一个参数
const removeLastParam = (url) => {
  const parsedUrl = new URL(url);
  const { searchParams } = parsedUrl;
  const paramsArray = Array.from(searchParams.entries());
  paramsArray.pop();
  const newSearchParams = new URLSearchParams(paramsArray);
  parsedUrl.search = newSearchParams.toString();
  const updatedUrl = parsedUrl.toString();
  return updatedUrl;
};

export async function middleware(req: NextRequest) {
  const dingCode = req.nextUrl.searchParams.get('code');
  const url: any = new URL(req.url);
  url.host = req.headers.get('host');
  if (dingCode) {
    return NextResponse.redirect(new URL(`/dingUserInfo?dingCode=${dingCode}&redirect=${removeLastParam(url)}`, req.url));
  }
  if (
    !req.nextUrl.pathname.startsWith('/api/') &&
    req.nextUrl.pathname.indexOf('.') <= 0 &&
    !req.nextUrl.pathname.includes('/image') &&
    !req.nextUrl.pathname.includes('/login') &&
    !req.nextUrl.pathname.includes('/dingUserInfo')
  ) {
    const verifiedToken = await verifyAuth(req).catch((err) => {
      // console.error(err.message);
    });
    if (!verifiedToken) {
      const goUrl = `https://canarysit.jrdaimao.com/#/loginos?redirect=${encodeURIComponent(url)}`;
      return NextResponse.redirect(new URL(goUrl));
      // return NextResponse.redirect(new URL('/login', req.url));
      // return new NextResponse(JSON.stringify(backMessage(null, 'token失效', '401')), { status: 200 });
    }
    return NextResponse.next();
  }
  return NextResponse.next();
}
